package com.warmlight.voicepacket.ui.search;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.warmlight.voicepacket.R;
import com.warmlight.voicepacket.adapter.SearchAdapter;
import com.warmlight.voicepacket.adapter.SearchHeaderAdapter;
import com.warmlight.voicepacket.base.BaseActivity;
import com.warmlight.voicepacket.data.SearchResult;
import com.warmlight.voicepacket.data.eventbus.AudioCompleted;
import com.warmlight.voicepacket.data.eventbus.CollectSingleAudio;
import com.warmlight.voicepacket.data.eventbus.ShareUnlock;
import com.warmlight.voicepacket.dbdata.DBSearchHistory;
import com.warmlight.voicepacket.dbmanager.DBSearchHistoryDaoHelp;
import com.warmlight.voicepacket.http.Callback;
import com.warmlight.voicepacket.http.HttpClient;
import com.warmlight.voicepacket.http.HttpConfig;
import com.warmlight.voicepacket.utils.JSONUtils;
import com.warmlight.voicepacket.widget.FooterListView;
import com.warmlight.voicepacket.widget.ScrollListView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import me.gujun.android.taggroup.TagGroup;
import okhttp3.Call;


public class SearchActivity extends BaseActivity implements View.OnClickListener {

    private EditText et_search;
    private TextView tv_search_cancel;
    private TagGroup tg_hot;
    private ImageView iv_search_clear;
    private TagGroup tg_history;
    private FooterListView list_search;
    private LinearLayout ll_hot_history;
    private RelativeLayout rl_search_result;
    private String mSearchKey;
    private int mPage;
    private LinearLayout linearLayout;
    private SearchHeaderAdapter searchHeaderAdapter;
    private SearchAdapter searchAdapter;
    private ArrayList<String> hotkey;
    private ArrayList<String> loglist;
    private TextView tv_look_more;
    private TextView tv_media_search;
    private String searchKey;
    private TextView tv_cover_like;
    private View view_line;
    private RelativeLayout rl_no_data;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null){
            searchKey = bundle.getString("searchKey");
        }
        initView();
        initListener();
        initData();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void xxxx(CollectSingleAudio collectSingleAudio){
        if (searchAdapter != null){
            searchAdapter.notifyCollect(collectSingleAudio.getAudioId());
        }
    }
    /**
     * 播放器播放完成回调
     * @param data
     */
    @Subscribe(threadMode = ThreadMode.MAIN)//(sticky = true)
    public void onEvent(AudioCompleted data){
        if (searchAdapter != null){
            searchAdapter.clearPlay();
        }
    }

    /**
     * 分享解锁回调
     * @param messageEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void XXX(ShareUnlock messageEvent) {
//        if (mTopicAdapter != null){
//            mTopicAdapter.updata(vp_topic.getCurrentItem(),messageEvent.islist,messageEvent.item,messageEvent.getCover_id());
//        }
        if (searchAdapter != null){

            searchAdapter.updata(messageEvent.islist,messageEvent.item,messageEvent.getCover_id());
        }

        if (searchHeaderAdapter != null){
            searchHeaderAdapter.updata(messageEvent.islist,messageEvent.item,messageEvent.getCover_id());
        }

    }

    private void initView() {
        et_search = (EditText) findViewById(R.id.et_search);
        et_search.setHint(searchKey);
        tv_search_cancel = (TextView) findViewById(R.id.tv_search_cancel);
        tg_hot = (TagGroup) findViewById(R.id.tg_hot);
        iv_search_clear = (ImageView) findViewById(R.id.iv_search_clear);
        tg_history = (TagGroup) findViewById(R.id.tg_history);
        list_search = (FooterListView) findViewById(R.id.list_search);
        ll_hot_history = (LinearLayout) findViewById(R.id.ll_hot_history);
        ll_hot_history.setVisibility(View.VISIBLE);
        rl_search_result = (RelativeLayout) findViewById(R.id.rl_search_result);
        rl_search_result.setVisibility(View.GONE);

        rl_no_data = (RelativeLayout) findViewById(R.id.rl_no_data);
        rl_no_data.setVisibility(View.GONE);

        linearLayout = new LinearLayout(getContext());
        AbsListView.LayoutParams params = new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        linearLayout.setLayoutParams(params);
        list_search.addHeaderView(linearLayout);
        initHead(linearLayout);
    }

    private void showSearch(boolean isResult){
        if (isResult){
            ll_hot_history.setVisibility(View.GONE);
            rl_search_result.setVisibility(View.VISIBLE);
        }else{
            ll_hot_history.setVisibility(View.GONE);
            rl_search_result.setVisibility(View.VISIBLE);
        }
    }
    /**
     * 头部信息列表
     * @param linearLayout
     */
    private void initHead(LinearLayout linearLayout) {
        View view = LayoutInflater.from(this).inflate(R.layout.header_search,linearLayout);
//        linearLayout.addView(view);
        ScrollListView listview_header_search = (ScrollListView) view.findViewById(R.id.listview_header_search);
        tv_look_more = (TextView) view.findViewById(R.id.tv_look_more);
        tv_media_search = (TextView) view.findViewById(R.id.tv_media_search);
        tv_cover_like = (TextView) view.findViewById(R.id.tv_cover_like);
        view_line = view.findViewById(R.id.view_line);

        List<SearchResult.DataBean.CoverListBean> coverListBeans = new ArrayList<>();

        searchHeaderAdapter = new SearchHeaderAdapter(this,coverListBeans);
        listview_header_search.setAdapter(searchHeaderAdapter);
    }


    private void initHeadData(final List<SearchResult.DataBean.CoverListBean> cover_list){
        if (cover_list.size()>3){
            tv_look_more.setVisibility(View.VISIBLE);
            searchHeaderAdapter.setList(cover_list.subList(0,3));
        }else{
            tv_look_more.setVisibility(View.GONE);
            searchHeaderAdapter.setList(cover_list);
            if (cover_list.size() == 0){
                tv_cover_like.setVisibility(View.GONE);
                view_line.setVisibility(View.GONE);
            }else{
                tv_cover_like.setVisibility(View.VISIBLE);
                view_line.setVisibility(View.VISIBLE);
            }
        }


        searchHeaderAdapter.notifyDataSetChanged();

        tv_look_more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv_look_more.setVisibility(View.GONE);
                searchHeaderAdapter.setList(cover_list);
                searchHeaderAdapter.notifyDataSetChanged();
            }
        });
    }

    private void initListener(){
        tv_search_cancel.setOnClickListener(this);
        iv_search_clear.setOnClickListener(this);
        et_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                search();
                return false;
            }
        });
        tg_hot.setOnTagClickListener(new TagGroup.OnTagClickListener() {
            @Override
            public void onTagClick(String tag) {
                et_search.setText(tag);
                et_search.setSelection(tag.length());
                search();
            }
        });

        tg_history.setOnTagClickListener(new TagGroup.OnTagClickListener() {
            @Override
            public void onTagClick(String tag) {
                et_search.setText(tag);
                et_search.setSelection(tag.length());
                search();
            }
        });
        list_search.setOnLastItemVisiableListener(new FooterListView.LastItemVisiableListener() {
            @Override
            public void onLastItemVisiable() {
                list_search.setResult(FooterListView.ActionResult.LOADING);
                searchResult();
            }
        });
        list_search.setOnFooterClickListener(new FooterListView.FooterClickListener() {
            @Override
            public void onFooterClicked() {
                list_search.setResult(FooterListView.ActionResult.LOADING);
                mPage--;
                searchResult();
            }
        });
    }

    private void search(){
        String searchKey = et_search.getText().toString().trim();
        if (TextUtils.isEmpty(searchKey)){
            showToast("请输入搜索词");
            return;
        }

        this.mSearchKey = searchKey;
        this.mPage = 0;
        if (searchAdapter != null){
            searchAdapter.setSearchKey(mSearchKey);
        }

        if (searchHeaderAdapter != null){
            searchHeaderAdapter.setSearchKey(mSearchKey);
        }
        searchResult();
        refreshHistory();
    }

    private void searchResult(){
        rl_no_data.setVisibility(View.GONE);
        String url = HttpConfig.SEARCH_RUSULT;
        TreeMap<String,String> map = new TreeMap<>();
        map.put("keyword",mSearchKey);
        mPage++;
        map.put("page",mPage+"");
        map.put("pagesize","10");
        HttpClient.post(url, map, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        list_search.setResult(FooterListView.ActionResult.ERROR);
                    }
                });
            }

            @Override
            public void onResponse(Call call, String response)   {
//                String s = response.body().string();
                final SearchResult searchResult = new Gson().fromJson(response, SearchResult.class);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        setSearchResult(searchResult);
                    }
                });
            }
        });
    }

    private void setSearchResult(SearchResult searchResult){
        if (searchResult.getCode() == 200){
            showSearch(true);
            SearchResult.DataBean data = searchResult.getData();
            if (data.isHas_more()){
                list_search.setResult(FooterListView.ActionResult.HAS_MORE);
            }else{
                list_search.setResult(FooterListView.ActionResult.NO_MORE);
            }
            List<SearchResult.DataBean.CoverListBean> cover_list = data.getCover_list();
            List<SearchResult.DataBean.AudioListBean> audio_list = data.getAudio_list();
            if (mPage == 1){
                initHeadData(cover_list);
                searchAdapter.setList(audio_list);
            }else{

                searchAdapter.addList(audio_list);
            }

            if (searchAdapter.getCount() == 0){
                tv_media_search.setVisibility(View.GONE);
                list_search.getFooterView().setVisibility(View.GONE);

                if (cover_list.size()==0){
                    rl_no_data.setVisibility(View.VISIBLE);
                }else{
                    rl_no_data.setVisibility(View.GONE);
                }

            }else{
                tv_media_search.setVisibility(View.VISIBLE);
                list_search.getFooterView().setVisibility(View.VISIBLE);
            }


            searchAdapter.notifyDataSetChanged();
        }
    }

    private void initData(){
//        String[] a = new String[]{"大波","bug明","sb波"};
//        tg_hot.setTags(a);
//        tg_history.setTags(a);
//        try {
//            List<DBSearchHistory> dbSearchHistories = DBSearchHistoryDaoHelp.queryBuildAll(this);
//        }catch (Exception e) {
//            e.printStackTrace();
//        }
        hotkey = new ArrayList<>();
        loglist = new ArrayList<>();
        List<SearchResult.DataBean.AudioListBean> audioListBeans = new ArrayList<>();
        searchAdapter = new SearchAdapter(this,audioListBeans);
        list_search.setAdapter(searchAdapter);

        initSearch();
    }

    private void refreshHistory(){
        DBSearchHistoryDaoHelp.insert(this,mSearchKey);

        loadHistory();
    }

    private void loadHistory(){
        List<DBSearchHistory> dbSearchHistories = DBSearchHistoryDaoHelp.queryBuildAll(this);
        tg_history.setTags(loglist);
    }

    private void initSearchHotHistory(ArrayList<String> hotkey, ArrayList<String> loglist){
        List<DBSearchHistory> dbSearchHistories = DBSearchHistoryDaoHelp.queryBuildAll(this);
        if (dbSearchHistories.size()>0){
            for (DBSearchHistory dbSearchHistory : dbSearchHistories){
                loglist.add(dbSearchHistory.getSearch());
            }
        }
        tg_hot.setTags(hotkey);
        tg_history.setTags(loglist);
    }

    private void clearHistory(){
        loglist.clear();
        tg_history.setTags(loglist);
        DBSearchHistoryDaoHelp.deleteAll(this);
        loadHistory();
    }

    private void initSearch(){
        String url = HttpConfig.SEARCH_INIT;
        HttpClient.post(url, new TreeMap<String, String>(), new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, String response)   {
//                String s = response.body().string();
                ArrayList<Map<String, String>> listMapByJson = JSONUtils.getListMapByJson(response);
                if (listMapByJson.size()>0){
                    Map<String, String> stringStringMap = listMapByJson.get(0);
                    if ("200".equals(stringStringMap.get("code"))){
                        String data = stringStringMap.get("data");
                        ArrayList<Map<String, String>> dataList = JSONUtils.getListMapByJson(data);
                        Map<String, String> dataMap = dataList.get(0);
                        final String hot_key = dataMap.get("hot_key");
                        String log_list = dataMap.get("log_list");
                        ArrayList<Map<String, String>> listMapByJson1 = JSONUtils.getListMapByJson(hot_key);


                        for (int i=0 ;i<listMapByJson1.size();i++){
                            hotkey.add(listMapByJson1.get(i).get(""));
                        }


                        ArrayList<Map<String, String>> listMapByJson2 = JSONUtils.getListMapByJson(log_list);


                        for (int i=0 ;i<listMapByJson2.size();i++){
                            loglist.add(listMapByJson2.get(i).get(""));
                        }

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                initSearchHotHistory(hotkey, loglist);
                            }
                        });
                    }
                }

            }
        });
    }

    private void clearSearchHistory(){
//        String url = HttpConfig.SEARCH_CLEAR;
//        HttpClient.post(url, new TreeMap<String, String>(), new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                String s = response.body().string();
//                ArrayList<Map<String, String>> listMapByJson = JSONUtils.getListMapByJson(s);
//                if (listMapByJson.size()>0){
//                    Map<String, String> stringStringMap = listMapByJson.get(0);
//                    if ("200".equals(stringStringMap.get("code"))){
//                        runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
                                clearHistory();
//                            }
//                        });
//                    }
//                }
//            }
//        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_search_cancel:
                finish();
                break;
            case R.id.iv_search_clear:
                if (tg_history != null && tg_history.getTags().length > 0) {
                    clearSearchHistory();
                }else{
                    showToast("暂无搜索历史记录");
                }
                //清空搜索历史
                break;
        }
    }
}
